<template>
  <div class="content-box" v-loading="!dataLoaded">
    <div class="content">
      <div class="group">
        <div class="header">
          <el-input readonly v-model="roomName">
            <template #append>
              <el-button :icon="Search" @click="dialogVisible = true" />
            </template>
          </el-input>
        </div>
        <div class="table-box" v-loading="loading">
          <ProTable
            ref="proTable"
            title="持卡人列表"
            rowKey="empid"
            :columns="columns"
            :request-api="getTableList"
            :data-callback="dataCallback"
            :tool-button="false"
            :select="_select"
            :click-row="_clickRow"
            :all-select-disabled="true"
            :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
            v-if="zNodes.length"
            :small="true"
          >
            <!-- Expand -->
            <template #expand="scope">
              {{ scope.row }}
            </template>
          </ProTable>
        </div>
      </div>
      <div class="main">
        <div class="table-box" v-loading="loading1">
          <ProTable
            ref="proTable1"
            title="房间列表"
            rowKey="sn"
            :columns="columns1"
            :request-api="getTableList1"
            :data-callback="dataCallback1"
            :tool-button="false"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 2, xl: 3 }"
            v-if="hotelSelList.length"
            :small="true"
          >
            <template #tableHeader="scope">
              <el-button type="primary" text :icon="CirclePlus" @click="openDialog">增加</el-button>
              <el-button type="danger" text :icon="Delete" @click="_batchDel(scope.selectedListIds)">删除</el-button>
            </template>
            <!-- Expand -->
            <template #expand="scope">
              {{ scope.row }}
            </template>
          </ProTable>
        </div>
      </div>
    </div>
    <TreeDialog
      :zNodes="zNodes"
      :dialogVisible="dialogVisible"
      :handleClose="handleClose"
      :submitCallback="getRoomId"
      v-if="zNodes.length"
    />
    <EmployeeDialog :dialogVisible="dialogVisible1" :handleClose="handleClose" :submitCallback="_submitEmployee" />
  </div>
</template>

<script setup lang="tsx" name="room">
import { onMounted, ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import TreeDialog from "./components/TreeDialog.vue";
import EmployeeDialog from "./components/EmployeeDialog.vue";
import { CirclePlus, Delete } from "@element-plus/icons-vue";
import { Search } from "@element-plus/icons-vue";
import { getRoomList, getAuthorizedRoomList, getHotelSelList, delRoom, addRoom } from "@/api/modules/smartLock/empower/room";
import { getRoomMapTree } from "@/api/modules/common";
import { ElMessage, ElMessageBox } from "element-plus";

const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dataLoaded = ref(false);
const loading = ref(false);
const loading1 = ref(false);
const proTable = ref();
const roomIds = ref([]);
const columns1: any = ref([]);
const proTable1 = ref();
const curRoom: any = ref({});
const zNodes: any = ref([]);
const hotelSelList = ref([]);
const roomName = ref("");

const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  return {
    list: records || [],
    total: page.total
  };
};

const dataCallback1 = (data: any) => {
  const { records, page } = data;
  loading1.value = false;
  return {
    list: curRoom.value.roomId ? records || [] : [],
    total: page.total
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading.value = true;
  return getRoomList({ ...newParams, mapndxs: roomIds.value });
};

const getTableList1 = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading1.value = true;
  return getAuthorizedRoomList({
    ...newParams,
    roomId: curRoom.value.roomId ?? ""
  });
};

const columns: any = [
  { type: "selection", fixed: "left", width: 60 },
  {
    prop: "clause",
    label: "",
    isShow: false,
    search: { el: "input" }
  },

  {
    prop: "roomCode",
    label: "房间号",
    minWidth: 120
  },
  {
    prop: "roomName",
    label: "房间描述",
    minWidth: 120
  }
];

/**
 * 多选框选择
 */
const _select = (selection, row) => {
  const selectedList = proTable.value.element.getSelectionRows();
  const isSel = selectedList.some(item => item.roomId === row.roomId);
  const lastSelItem = selection.shift();
  if (selection.length) {
    proTable.value.element.toggleRowSelection(lastSelItem, false);
  }
  curRoom.value = isSel ? row : {};
  proTable1.value.clearSelection();
  proTable1.value.getTableList();
};

/**
 * 单击行
 */
const _clickRow = row => {
  const selectedList = proTable.value.element.getSelectionRows();
  const isSel = selectedList.some(item => item.roomId === row.roomId);
  proTable.value.clearSelection();
  proTable.value.element.toggleRowSelection(row, isSel ? false : true);
  curRoom.value = !isSel ? row : {};
  proTable1.value.clearSelection();
  proTable1.value.getTableList();
};

const _batchDel = async (selectedListIds: string[]) => {
  console.log(selectedListIds);
  if (!selectedListIds.length) {
    ElMessage.error("请选择人员");
    return false;
  }
  ElMessageBox.confirm(`是否删除所选人员?`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    try {
      const res = await delRoom(selectedListIds);
      const { v1, v2 } = res.data;
      ElMessage.success(`删除成功：${v1},失败：${v2}`);

      proTable1.value.clearSelection();
      proTable1.value.getTableList();
    } catch (error) {
      console.log(error);
    }
  });
};

const _submitEmployee = async (empIds: string[], datetimerange) => {
  try {
    const res = await addRoom({
      empIds,
      roomId: curRoom.value.roomId,
      begin: datetimerange[0],
      end: datetimerange[1]
    });
    const { v1, v2 } = res.data;
    dialogVisible1.value = false;
    ElMessage.success(`增加成功：${v1},失败：${v2}`);
    proTable1.value.clearSelection();
    proTable1.value.reset();
  } catch (error) {
    console.log(error);
  }
};

/**
 * 增加房间弹窗
 */
const openDialog = () => {
  if (!curRoom.value?.roomId) {
    ElMessage.error("请先选择房间");
    return false;
  }
  dialogVisible1.value = true;
};

/**
 * 获取roomId
 */
const getRoomId = (name, ids) => {
  roomName.value = name;
  roomIds.value = ids;
  dialogVisible.value = false;
  curRoom.value = {};
  proTable.value.clearSelection();
  proTable.value.getTableList();
  proTable1.value.clearSelection();
  proTable1.value.reset();
};

/**
 * 关闭弹窗
 */
const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
};

/**
 * 获取酒店选择下拉列表
 */
const getHotelSelData = async () => {
  try {
    const res = await getHotelSelList();
    hotelSelList.value = res.data.map(item => {
      return {
        label: item.value,
        value: item.key
      };
    });
    hotelSelList.value.unshift({
      label: "全部",
      value: ""
    });
    columns1.value = [
      { type: "selection", fixed: "left", width: 60 },
      {
        prop: "hotelId",
        label: "酒店名称",
        isShow: false,
        enum: hotelSelList.value,
        search: {
          el: "select",
          defaultValue: hotelSelList.value.length ? hotelSelList.value[0].value : ""
        },
        width: 120
      },

      {
        prop: "sn",
        isShow: false
      },
      {
        prop: "empcode",
        label: "职工号",
        minWidth: 200
      },
      {
        prop: "empName",
        label: "姓名",
        minWidth: 200
      },
      {
        prop: "begindatetime",
        label: "有效开始时间",
        minWidth: 200
      },
      {
        prop: "enddatetime",
        label: "有效结束时间",
        minWidth: 200
      }
    ];
  } catch (error) {
    columns1.value = [
      { type: "selection", fixed: "left", width: 60 },
      {
        prop: "sn",
        isShow: false
      },
      {
        prop: "empcode",
        label: "职工号",
        minWidth: 200
      },
      {
        prop: "empName",
        label: "姓名",
        minWidth: 200
      },
      {
        prop: "begindatetime",
        label: "有效开始时间",
        minWidth: 200
      },
      {
        prop: "enddatetime",
        label: "有效结束时间",
        minWidth: 200
      }
    ];
    console.log(error);
  }
};
const getRoomMapData = async () => {
  try {
    const res = await getRoomMapTree();
    zNodes.value = res.data;
    if (zNodes.value.length) {
      roomName.value = zNodes.value[0].name;
      roomIds.value = getFlatMapData(zNodes.value).map(item => item.id);
    }
  } catch (error) {
    console.log(error);
  }
};

/**
 * 展开树
 */
const getFlatMapData = (list: any) => {
  let newList = JSON.parse(JSON.stringify(list));
  return newList.flatMap((item: any) => [item, ...(item.children ? getFlatMapData(item.children) : [])]);
};

onMounted(async () => {
  Promise.all([getHotelSelData(), getRoomMapData()]).then(() => {
    dataLoaded.value = true;
  });
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
